//
// Created by wormtql on 2020/11/28.
//

#include <map>
#include <string>
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
#include <sstream>
#include <iostream>
#include <set>
#include <cmath>

#define INF 0x3f3f3f3f

using namespace std;

void parse_csv_line(char * line, vector<string> & data) {
    int state = 0;
    char buf[1000] = { 0 };
    int l = 0;

    int i = 0;
    while (line[i]) {
        if (state == 0) {
            if (line[i] == ',') {
                state = 1;
            } else {
                buf[l++] = line[i];
                i++;
            }
        } else if (state == 1) {
            buf[l] = 0;
            l = 0;
            data.push_back(string(buf));
            i++;
            state = 0;
        }
    }
    if (l != 0) {
        buf[l] = 0;
        data.emplace_back(buf);
    }
}

char buf[100000];
int matrix[10000][10000];
int main(int argc, char * argv[]) {
    if (argc < 3) {
        printf("merge results from \'directed_dis_cache\'\n\n");
        printf("app output.csv file1.csv file2.csv ...\n\n");
    }

    memset(matrix, INF, sizeof(matrix));

    ofstream output(argv[1]);

    int count = 0;
    for (int i = 2; i < argc; i++) {
        ifstream file(argv[i]);

        int j = 0;
        while (file.getline(buf, 100000)) {
            vector<string> temp;
            parse_csv_line(buf, temp);
            count = temp.size();
            for (int k = 0; k < temp.size(); k++) {
                int value = atoi(temp[k].c_str());
                matrix[j][k] = min(matrix[j][k], value);
            }

            j++;
        }

        file.close();
    }

    for (int i = 0; i < count; i++) {
        for (int j = 0; j < count; j++) {
            output << matrix[i][j];
            if (j != count - 1) {
                output << ",";
            }
        }
        output << endl;
    }

    output.close();

    return 0;
}